package com.chwn.curiousdiary.ui.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.bean.BannerBean;
import com.chwn.curiousdiary.bean.StoryListBean;
import com.chwn.curiousdiary.bean.StoryTypeBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.gloable.UserUtils;
import com.chwn.curiousdiary.ui.main.contract.HomeContract;
import com.chwn.curiousdiary.ui.main.presenter.HomePresenter;
import com.chwn.curiousdiary.ui.story.activity.StoryListActivity;
import com.chwn.curiousdiary.utils.GlideImageLoader;
import com.chwn.curiousdiary.utils.ImgLoadUtil;
import com.chwn.harulib.mvp.base.BaseMVPFragment;
import com.chwn.harulib.util.TimeUtils;
import com.umeng.analytics.MobclickAgent;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by Myshikin on 2017/3/20.
 * desc:
 */
public class HomeFragment extends BaseMVPFragment<HomePresenter> implements HomeContract.View,
        View.OnClickListener {

    // 轮播图
    private Banner mBanner;

    private int ids[] = new int[]{R.drawable.icon_l1, R.drawable.icon_l2, R.drawable.icon_l3
            , R.drawable.icon_l4, R.drawable.icon_l5, R.drawable.icon_l6
            , R.drawable.icon_l7, R.drawable.icon_l8, R.drawable.icon_l9, R.drawable.icon_l10,};

    /**
     * 刷新界面标识
     */
    private boolean isRefresh = true;
    // private View           headView;
    private int            firstHeight;
    private RelativeLayout mWrap;

    private RelativeLayout mUserCoin;
    private TextView       mUserCoinTV;
    private TextView       mBabyAgeTV;
    private TextView       mUserNameTV;
    private ImageView      userImg;
    private ImageView      userLevel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_home;

    }

    @Override
    protected void initContentView() {
        initInflateView(mInflateContentView);

    }

    @Override
    public void onStart() {
        super.onStart();
        initUserData();
    }

    private void initUserData() {
        User user = DiaryApplication.mInstance.getmUser();
        if (user != null && user.getUserToken() != null && !TextUtils.isEmpty(user.getBabybirth())) {
            ImgLoadUtil.displayCircle(userImg, "", "0".equals(user.getBabysex()) ? R.drawable.icon_girl : R.drawable.icon_boy);
            String level = user.getUserLevel();
            String babybirth = user.getBabybirth();
            mUserCoinTV.setText(user.getCoinCount());
            mBabyAgeTV.setText(TimeUtils.getAge((long) Integer.parseInt(babybirth)));
            if (!TextUtils.isEmpty(level)) {
                int i = Integer.parseInt(level.split("\\.")[1]);
                if (i == 0) {
                    userLevel.setVisibility(View.GONE);
                } else {
                    userLevel.setVisibility(View.VISIBLE);
                    userLevel.setImageResource(ids[i - 1]);
                }
            } else {
                userLevel.setVisibility(View.GONE);
            }
            mUserCoin.setVisibility(View.VISIBLE);
            mBabyAgeTV.setVisibility(View.VISIBLE);
            mUserNameTV.setText("好奇宝宝");
        } else {
            userLevel.setVisibility(View.GONE);
            mUserCoin.setVisibility(View.GONE);
            mBabyAgeTV.setVisibility(View.GONE);
            mUserNameTV.setText("未登录");
        }
    }


    /**
     * 故事分类目前写死在布局中，将动态添加故事分类代码暂时注掉，根据后期需求可做相应修改
     * @param inflateView
     */
    private void initInflateView(View inflateView) {
        mBanner = (Banner) inflateView.findViewById(R.id.banner_home);
        mWrap = (RelativeLayout) inflateView.findViewById(R.id.rl_wrap);
        mUserCoin = (RelativeLayout) inflateView.findViewById(R.id.user_coin);
        mUserCoinTV = (TextView) inflateView.findViewById(R.id.tv_user_coin);
        mBabyAgeTV = (TextView) inflateView.findViewById(R.id.tv_baby_age);
        mUserNameTV = (TextView) inflateView.findViewById(R.id.tv_username);

        userImg = (ImageView) inflateView.findViewById(R.id.user_head);
        userLevel = (ImageView) inflateView.findViewById(R.id.iv_user_level);
        inflateView.findViewById(R.id.iv_commend).setOnClickListener(this);
        inflateView.findViewById(R.id.iv_snailman).setOnClickListener(this);
        inflateView.findViewById(R.id.iv_newset).setOnClickListener(this);
        inflateView.findViewById(R.id.iv_build).setOnClickListener(this);
        inflateView.findViewById(R.id.iv_fancy).setOnClickListener(this);
        inflateView.findViewById(R.id.iv_life).setOnClickListener(this);
        inflateView.findViewById(R.id.iv_book).setOnClickListener(this);
        inflateView.findViewById(R.id.iv_animal).setOnClickListener(this);
        inflateView.findViewById(R.id.ll_user_img).setOnClickListener(this);
    }

    @Override
    public void onRequestError(Throwable e) {
        super.onRequestError(e);
    }

    @Override
    protected void getData() {
        showContentView();
        mPresenter.getBannerList();
        mPresenter.getStoryType();
    }

    @Override
    public void showBannerList(List<BannerBean> bannerList) {
        mBanner.setImages(bannerList)
                .setImageLoader(new GlideImageLoader())
                .setDelayTime(Constant.BANNER_DELAY_TIME)
                .setOnBannerClickListener(new OnBannerClickListener() {
                    @Override
                    public void OnBannerClick(int position) {

                    }
                })
                .start();
        /*if (!(mStoryAdapter.getDatas().size() > 0)) {
            mContentRV.noMoreLoading();
        }*/
        showContentView();
        mIsFirst = false;
    }

    @Override
    public void showGuessLikeList(List<StoryListBean> storyList) {

    }

    @Override
    public void showStoryType(List<StoryTypeBean> storyTypeList) {

    }

    /**
     * 事件响应
     * @param event
     */
    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.UPDATE_USER_INFO:
                if (mUserCoinTV != null) {
                    initUserData();
                }
                break;
            case CustomEvent.UPDATE_COIN_INFO:
                if (mUserCoinTV != null) {
                    initUserData();
                }
                break;
        }
    }

    /**
     * 点击事件处理
     * @param view
     */
    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.ll_user_img) {
            UserUtils.isLogin(mActivity);
            return;
        }

        HashMap<String, String> map = new HashMap<>();

        switch (view.getId()) {
            case R.id.iv_commend:
                enterStoryTypePage(Constant.COMMEND_TAG);
                map.put("type", "个性推荐");
                break;
            case R.id.iv_snailman:
                enterStoryTypePage(Constant.ADVENTURE_TAG);
                map.put("type", "蜗牛小战警");
                break;
            case R.id.iv_newset:
                enterStoryTypePage(Constant.NEW_TAG);
                map.put("type", "最新故事");
                break;
            case R.id.iv_build:
                enterStoryTypePage(Constant.BUILD_TAG);
                map.put("type", "童话城堡");
                break;
            case R.id.iv_fancy:
                enterStoryTypePage(Constant.FANCY_TAG);
                map.put("type", "奇幻传说");
                break;
            case R.id.iv_life:
                enterStoryTypePage(Constant.LIFE_TAG);
                map.put("type", "生活奥秘");
                break;
            case R.id.iv_book:
                enterStoryTypePage(Constant.CHINABOOK_TAG);
                map.put("type", "国学经典");
                break;
            case R.id.iv_animal:
                enterStoryTypePage(Constant.ANIMAL_TAG);
                map.put("type", "萌趣生物");
                break;
        }

        MobclickAgent.onEvent(getContext(), "classify_click_count", map);
    }

    /**
     * 跳转至相应故事分类界面
     * @param position
     */
    private void enterStoryTypePage(int position) {
        Intent intent = new Intent(getActivity(), StoryListActivity.class);
        intent.putExtra(Constant.JUMP_TYPE, position);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
